package controller

import (
	"blog2021/configs"
	"blog2021/model"
	"blog2021/tools/logger"
	"encoding/xml"
	"io/ioutil"
	"os"
	"path"

	"github.com/gin-gonic/gin"
)

type FeedItem struct {
	XMLName     xml.Name `xml:"item"`
	Title       string   `xml:"title"`
	Description string   `xml:"description"`
	Author      string   `xml:"author"`
	PubDate     string   `xml:"pubDate"`
	Link        string   `xml:"link"`
	Guid        string   `xml:"guid"`
}

type FeedChannel struct {
	Title       string     `xml:"title"`
	Link        string     `xml:"link"`
	Description string     `xml:"description"`
	Language    string     `xml:"language"`
	Items       []FeedItem `xml:"item"`
}

type FeedTemplate struct {
	XMLName xml.Name    `xml:"rss"`
	Version string      `xml:"version,attr"`
	Channel FeedChannel `xml:"channel"`
}

func Feed(c *gin.Context) {
	feedTemplate := FeedTemplate{
		Version: "2.0",
		Channel: FeedChannel{
			Title:       "Ningto's Blog",
			Link:        "https://ningto.com",
			Description: "Ningto's Blog Feed",
			Language:    "zh-cn",
			Items:       []FeedItem{},
		},
	}

	posts := model.GetAllPost()
	for _, post := range posts {
		item := FeedItem{
			Title:       post.Title,
			Description: post.Profile,
			Author:      post.Author,
			PubDate:     post.CreatedAt.Format("2006-01-02 15:04:05"),
			Link:        "https://ningto.com/post/" + post.Id,
			Guid:        post.Id,
		}
		feedTemplate.Channel.Items = append(feedTemplate.Channel.Items, item)
	}

	b, err := xml.MarshalIndent(feedTemplate, "", "    ")
	if err != nil {
		logger.Error(err)
		ResponseMessage(c, "ERROR", err.Error())
		return
	}

	feedPath := path.Join(configs.AppDir("view/static"), "feed.xml")
	ioutil.WriteFile(feedPath, b, os.ModePerm)
	c.JSON(200, gin.H{
		"url": "/static/feed.xml",
	})
}
